<?php
class OrderController extends BaseController {
    protected $layout = 'layouts.admin';
	public function index()
	{
		$query = Order::where('id','>', 0);
		$word = Input::get('search_word');
		$search_type = Input::get('search_type');
		if( Input::get('search_word') != '' ){			
			if( strpos($search_type,'.') ){
				list($table,$col) = explode('.', $search_type);
				$query = $query->whereHas($table,function($q) use($col, $word) {
					$q->where($col, $word);
				});
			}else{
				$query = $query->where($search_type, $word);
			}
		}
		$qfilter = Input::get('filter');
		if ( is_array($qfilter) && count($qfilter)){
			foreach($qfilter as $filter_name=>$filter_value ) {
				if($filter_value == 'ALL') {
					continue;
				}
				if( strpos($filter_name,'.') ){
					list($table,$col) = explode('.', $filter_name);
					$query = $query->whereHas($table,function($q) use($col, $filter_value) {
						$q->where($col, $filter_value);
					});
				}else{
					$query = $query->where($filter_name, $filter_value);
				}
			}
		}
		$qsort= Input::get('sort', array('created_at'=>'desc'));
		if ( is_array($qsort) && count($qsort)){
			foreach($qsort as $sort_name=>$sort_order ) {
				if ( strpos($sort_name, '.')){
					list($table,$col) = explode('.', $sort_name);
				}else {
					$query = $query->orderBy($sort_name, $sort_order);
				}
			}
		}
		$orders  = $query->paginate(Config::get('app.page_row'));

		$works = WorkflowNode::all();
		$this->layout->content = view::make('admin.order.index')->with(compact('orders','works','word','search_type','qsort','qfilter'));
	}
	
	public function update($id, $step)
	{
		if ( Input::server('REQUEST_METHOD') == 'POST') {
			$wf = new Workflow();
			foreach ( ['order_id' => $id,
				'workflow_node_id' => $step,
				'user_id' => Auth::user()->id,
				'user_name' => Auth::user()->account,
				'memo'	=> Input::get('memo')] as $k=>$v) {
		
				$wf->$k = $v;
			}
			$wf->save();
			return Redirect::to( route('admin.order.index') );
		}else{
			$order = Order::find($id);
			$workflows = Workflow::where('order_id', '=', $id)->orderBy('created_at', 'DESC')->get();
			$node = WorkflowNode::find($step);
			$this->layout->content = view::make('admin.order.update')->with(compact('order','node', 'workflows'));
		}
	}
}